﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Collections;
using System.Xml.Linq;
using ProductKeyManager.DB;

namespace ProductKeyManager.XML
{
    public static class XmlHandler
    {

        /// <summary>
        /// Imports XML file from the specified URI and imports product keys.
        /// Set to work off of MSDN Product Key XML
        /// </summary>
        /// <param name="fileuri">URI of xml file being processed</param>
        /// <returns>Collection of keys within specified XML file</returns>
        public static IEnumerable<Product> ImportMsdnXml(Uri fileUri)
        {
            List<Product> importedkeys = new List<Product>();
            List<string> names = new List<string>();
            XmlReader reader = XmlReader.Create(fileUri.ToString());
            while (reader.ReadToFollowing("Product_Key"))
            {
                Product newKey = null;
                if (reader.GetAttribute("Name") != null && reader.GetAttribute("Key") != null)
                {
                    string allocto = "Not Allocated";
                    if (reader.GetAttribute("AllocatedTo") != null)
                    {
                        allocto = reader.GetAttribute("AllocatedTo");
                    }
                    if (names.Contains(reader.GetAttribute("Name")))
                    {
                        importedkeys[names.IndexOf(reader.GetAttribute("Name"))].Keys.Add(new Key { KeyCode = reader.GetAttribute("Key"), AllocatedTo = allocto });
                    }
                    else
                    {
                        newKey = new Product { Name = reader.GetAttribute("Name") };

                        newKey.Keys.Add(new Key { KeyCode = reader.GetAttribute("Key"), AllocatedTo = allocto });
                        importedkeys.Add(newKey);
                        names.Add(newKey.Name);
                    }
                }
            }


            return importedkeys;
        }

        public static IEnumerable<Product> ImportProductKeyManagerXml(Uri fileUri)
        {
            List<Product> import = new List<Product>();
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(fileUri.ToString());
                XmlNode node = doc.SelectSingleNode("ProductKeys");
                XmlNodeList Products = node.ChildNodes;
                foreach (XmlNode prod in Products)
                {
                    Product newProd = new Product { Name = prod.Attributes["Name"].Value };

                    foreach (XmlNode key in prod.ChildNodes)
                    {
                        newProd.Keys.Add(new ProductKeyManager.DB.Key { KeyCode = key.Attributes["KeyCode"].Value, AllocatedTo = key.Attributes["AllocatedTo"].Value });
                    }
                    import.Add(newProd);
                }
            }
            catch (Exception)
            {
                try
                {
                    import = (List<Product>)ImportMsdnXml(fileUri);
                }
                catch (Exception)
                {
                }
            }

            return import;
        }

        public static string ExportProductKeyManagerXml(IEnumerable<Product> ProductKeys)
        {
            return ExportProductKeyManagerXml(ProductKeys, false, "");
        }

        public static string ExportProductKeyManagerXml(IEnumerable<Product> ProductKeys, bool GenerateStyleSheet, string filename)
        {
            string xmlResult = "<?xml version=\"1.0\" standalone=\"yes\" ?>" + Environment.NewLine;
            if (GenerateStyleSheet && !String.IsNullOrEmpty(filename))
            {
                xmlResult += "<?xml-stylesheet type=\"text/xsl\" href=\"" + filename + ".xsl\"?>" + Environment.NewLine;
            }
            XElement xml = new XElement("ProductKeys",
                               from p in ProductKeys
                               select new XElement("Product",
                                          new XAttribute("Name", p.Name),
                                          from k in p.Keys
                                          select new XElement("Key",
                                                     new XAttribute("KeyCode", k.KeyCode),
                                                     new XAttribute("AllocatedTo", k.AllocatedTo)
                                                     )
                                                 )
                                      );

            return xmlResult + xml.ToString();
        }

        public static string ExportMsdnXml(IEnumerable<Product> ProductKeys)
        {
            return ExportMsdnXml(ProductKeys, false, "");
        }

        public static string ExportMsdnXml(IEnumerable<Product> ProductKeys, bool GenerateStyleSheet, string filename)
        {
            string xmlResult = "<?xml version=\"1.0\" standalone=\"yes\" ?>" + Environment.NewLine;
            if (GenerateStyleSheet && !String.IsNullOrEmpty(filename))
            {
                xmlResult += "<?xml-stylesheet type=\"text/xsl\" href=\"" + filename + ".xsl\"?>" + Environment.NewLine;
            }
            List<object> elements = new List<object>();

            foreach (Product prod in ProductKeys)
            {
                foreach (Key key in prod.Keys)
                {
                    XElement element = new XElement("Product_Key",
                                               new XAttribute("Name", prod.Name),
                                               new XAttribute("Key", key.KeyCode),
                                               new XAttribute("AllocatedTo", key.AllocatedTo));
                    elements.Add(element);
                }
            }

            XElement xml = new XElement("Your_Product_Keys", elements.ToArray());

            return xmlResult + xml.ToString();
        }

    }
}
